﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace T03ChatClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Socket clientSocket = null;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtName.Text.Trim()))
            {
                MessageBox.Show("请输入聊天昵称!");
                return;
            }
            if (clientSocket == null)
            {
                try
                {
                    IPAddress ip = IPAddress.Parse("127.0.0.1");
                    IPEndPoint iep = new IPEndPoint(ip, 13000);
                    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //异步(新开线程，处理网络连接)
                    clientSocket.BeginConnect(iep, (args) =>
                    {
                        if (args.IsCompleted)
                        {
                            byte[] bytesend = new byte[4096];
                            //访问UI线程中的内容，异步更新界面
                            TxtName.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                bytesend = Encoding.UTF8.GetBytes(TxtName.Text.Trim() + "$");
                                if (clientSocket != null & clientSocket.Connected)
                                {
                                    clientSocket.Send(bytesend);
                                    TxtName.IsEnabled = false;
                                    TxtSending.Focus();
                                    Thread t = new Thread(DataFromServer);
                                    t.IsBackground = true;
                                    t.Start();
                                }
                                else
                                {
                                    MessageBox.Show("服务器已关闭");
                                    clientSocket = null;
                                }
                            }));
                        }
                    }, null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }

            }
        }

        private void DataFromServer()
        {
            showMsg("服务器连接开启...");
            bool isListen = true;
            try
            {
                while (isListen)
                {
                    string datafromserver = null;
                    byte[] buf = new byte[4096];
                    int len = clientSocket.Receive(buf);
                    datafromserver = Encoding.UTF8.GetString(buf, 0, len);
                    if (datafromserver.StartsWith("#") && datafromserver.EndsWith("#"))
                    {
                        datafromserver = datafromserver.Substring(1, datafromserver.Length - 2);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MessageBox.Show("用户名【" + datafromserver + "】已存在，请重新输入！");
                            TxtName.IsEnabled = true;
                            TxtName.Focus();
                        }));
                        isListen = false;
                        if(clientSocket!=null&clientSocket.Connected)
                        {
                            clientSocket.Send(Encoding.UTF8.GetBytes("$"));
                            clientSocket.Close();
                            clientSocket = null;
                        }
                    }
                    else
                    {
                        showMsg(datafromserver);
                    }
                }
            }
            catch (Exception e)
            {
                isListen = false;
                if (clientSocket != null & clientSocket.Connected)
                {
                    clientSocket.Send(Encoding.UTF8.GetBytes("$"));
                 Debug.WriteLine(e.ToString());
                }    
            }
        }

        private void showMsg(string msg)
        {
            TxtReceive.Dispatcher.BeginInvoke(new Action(() =>
            {
                TxtReceive.Text += Environment.NewLine + msg;
                TxtReceive.ScrollToEnd();
            }));
        }

        private void BtnSend_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TxtSending.Text.Trim()))
            {
                MessageBox.Show("输入内容为空，请重新输入!");
                return;
            }
            if(clientSocket!=null&&clientSocket.Connected)
            {
                clientSocket.Send(Encoding.UTF8.GetBytes(TxtSending.Text.Trim() + "$"));
                TxtSending.Text = "";
            }
            else
            {
                MessageBox.Show("服务器已关闭或未连接!");
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            TxtSending.Focus();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if(clientSocket!=null&&clientSocket.Connected)
            {
                clientSocket.Send(Encoding.UTF8.GetBytes("$"));
            }
        }
    }
}
